package com.xzz.service.impl;

import com.alibaba.fastjson.JSON;
import com.xzz.domain.Login;
import com.xzz.dto.LoginDto;
import com.xzz.mapper.LoginMapper;
import com.xzz.result.JSONResult;
import com.xzz.service.ILoginService;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.xzz.util.HttpUtil;
import org.springframework.stereotype.Service;

import java.util.Map;

/**
 * <p>
 * 登录表 服务实现类
 * </p>
 *
 * @author xzz
 * @since 2022-08-26
 */
@Service
public class LoginServiceImpl extends ServiceImpl<LoginMapper, Login> implements ILoginService {

    @Override
    public JSONResult login(LoginDto dto) {
        // 发送http请求，给security，去获取包含token的各种数据
        String tokenUrlStr="http://localhost:10030/oauth/token?client_id=%s&client_secret=%s&grant_type=password&username=%s&password=%s";
        String security="123";
        String clientId=null;
        if (dto.getType()==0){
            clientId="backstage";
        }else {
            clientId="website";
        }
        String username = dto.getUsername();
        String password = dto.getPassword();

        String tokenUrl = String.format(tokenUrlStr, clientId, security, username, password);
        // 发送http请求，给security，去获取包含token的各种数据
        String tokenJSON = HttpUtil.sendPost(tokenUrl, null);
        // 返回token等相关参数给前端
        Map<String, Object> map = JSON.parseObject(tokenJSON, Map.class);
        if(map.containsKey("error")){ // 包含error
            // 抛错
            return JSONResult.error("账号密码错误！！");
        }
        //当前时间和过期倒计时算出最终时间
        Long expireTime = System.currentTimeMillis() + Long.valueOf((Integer)map.get("expires_in"));

        map.put("expiresTime", expireTime.toString());

        // 正确返回
        return JSONResult.success(map);

    }
}
